package com.shbaiche.bifenba.ui.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.video.ArticleGroupListMessage;
import com.shbaiche.bifenba.model.video.ArticleGroupVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.GirlFragment;
import com.shbaiche.bifenba.ui.base.BaseFragment;
import com.shbaiche.bifenba.ui.video.VideoTeamFragment;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.SystemUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidbase.base.XFragmentAdapter;
import cn.droidlover.xstatecontroller.XStateController;
import okhttp3.Call;

public class HomeActivity extends BaseFragment {

    @BindView(R.id.layout)
    View layout;
    private CategoryTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter adapter;
    private TextView mEditLayout;
    private ImageView ImgHomeCategory;
    XStateController contentLayout;
    List<ArticleGroupVo> catalogs = new ArrayList<ArticleGroupVo>();
    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;
    private TextView searchTv;

    public static int update = 0;

    public static HomeActivity newInstance() {
        return new HomeActivity();
    }


    @Override
    public void onResume() {
        if (update == 1) {
            update = 0;
            catalogs = new ArrayList<ArticleGroupVo>();

            String homeStr = SystemUtil.loadPreference("home");
            if (!TextUtils.isEmpty(homeStr)) {
                String[] array = homeStr.split("\\^");
                if (array != null) {
                    try {
                        ArticleGroupVo vo = null;
                        for (int i = 0; i < array.length; i++) {
                            String json = array[i];
                            vo = new ArticleGroupVo();
                            JSONObject obj = new JSONObject(json);
                            String name = obj.getString("name");
                            Long mId = obj.getLong("id");
                            vo.setName(name);
                            vo.setId(mId);
                            catalogs.add(vo);
                        }
                        adapter.notifyDataSetChanged();
                        tabs.notifyDataSetChanged();
                    } catch (Exception e) {

                    }
                }
            }

        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消动态网络变化广播接收器的注册
        getActivity().unregisterReceiver(networkChangeReceiver);
    }


    private void load() {
        ArticleGroupListMessage msg = new ArticleGroupListMessage();
        msg.setType(ArticleGroupVo.Type.ARTICLE);

        NetApi.videoTitle(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onResponse(TransMessage response, int id) {

                contentLayout.showContent();
                catalogs.clear();

                Gson gson = new Gson();
                ArticleGroupListMessage msg = gson.fromJson(response.getMessage(), ArticleGroupListMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                    List<ArticleGroupVo> groupList = msg.getGroupList();
                    List<ArticleGroupVo> otherGroup = msg.getOtherGroup();
                    if (groupList != null && groupList.size() > 0) {
                        String homeStr = SystemUtil.loadPreference("home");
                        StringBuffer homeSb = new StringBuffer();

                        for (int i = 0; i < groupList.size(); i++) {
                            ArticleGroupVo vo = groupList.get(i);
                            Long myId = 0l;
                            if (vo.getId() != null) {
                                myId = vo.getId();
                            }
                            String type = "足球";
                            if (vo.getGameType() != null) {
                                type = vo.getGameType().getText();
                            }
                            homeSb.append("{\"name\":\"" + vo.getName() + "\",\"id\":\"" + myId + "\",\"gametype\":\"" + type + "\"}");
                            if (i != groupList.size() - 1) {
                                homeSb.append("^");
                            }
                            catalogs.add(vo);
                        }
                        if (TextUtils.isEmpty(homeStr)) {
                            SystemUtil.savePreference("home", homeSb.toString());
                        }

                        pager.setAdapter(adapter);
                        tabs.setViewPager(pager);
                    }
                    if (otherGroup != null && otherGroup.size() > 0) {
                        String homeStr = SystemUtil.loadPreference("otherGroup");
                        StringBuffer otherGroupSB = new StringBuffer();

                        for (int i = 0; i < otherGroup.size(); i++) {
                            ArticleGroupVo vo = otherGroup.get(i);
                            Long myId = 0l;
                            if (vo.getId() != null) {
                                myId = vo.getId();
                            }
                            String type = "足球";
                            if (vo.getGameType() != null) {
                                type = vo.getGameType().getText();
                            }

                            otherGroupSB.append("{\"name\":\"" + vo.getName() + "\",\"id\":\"" + myId + "\",\"gametype\":\"" + type + "\"}");
                            if (i != otherGroup.size() - 1) {
                                otherGroupSB.append("^");
                            }
                        }
                        if (TextUtils.isEmpty(homeStr)) {
                            SystemUtil.savePreference("otherGroup", otherGroupSB.toString());
                        }
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        tabs = (CategoryTabStrip) layout.findViewById(R.id.category_strip);
        pager = (ViewPager) layout.findViewById(R.id.view_pager_home);
        ImgHomeCategory = (ImageView) layout.findViewById(R.id.icon_home_category);
        contentLayout = (XStateController) layout.findViewById(R.id.contentLayout);
        searchTv = (TextView) layout.findViewById(R.id.home_title_edit);

        mEditLayout = (TextView) layout.findViewById(R.id.home_title_edit);

        adapter = new MyPagerAdapter(getChildFragmentManager());

        mEditLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(getActivity(), SearchActivity.class);
                startActivity(it);
            }
        });
        ImgHomeCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(getActivity(), ChannelActivity.class);
                startActivity(it);
            }
        });
        contentLayout.loadingView(View.inflate(getActivity(), R.layout.view_loading, null));

        if (contentLayout != null) {
            contentLayout.showLoading();
        }
        String homeStr = SystemUtil.loadPreference("home");
        if (!TextUtils.isEmpty(homeStr)) {
            contentLayout.showContent();
            String[] array = homeStr.split("\\^");
            if (array != null) {
                try {
                    ArticleGroupVo vo = null;
                    for (int i = 0; i < array.length; i++) {
                        String json = array[i];
                        vo = new ArticleGroupVo();
                        JSONObject obj = new JSONObject(json);
                        String name = obj.getString("name");
                        Long mId = obj.getLong("id");
                        vo.setName(name);
                        vo.setId(mId);
                        catalogs.add(vo);
                    }
                    pager.setAdapter(adapter);
                    pager.setOffscreenPageLimit(adapter.getCount());
                    tabs.setViewPager(pager);
                } catch (Exception e) {

                }
            }
        } else {
            load();
        }

        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");

        networkChangeReceiver = new NetworkChangeReceiver();
        getActivity().registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_home;
    }

    public class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String title = "";
            if (catalogs.get(position) != null && !TextUtils.isEmpty(catalogs.get(position).getName())) {
                title = catalogs.get(position).getName();
            }

            return title;
        }

        @Override
        public int getCount() {
            return catalogs.size();
        }

        @Override
        public Fragment getItem(int position) {
            HomeFragment fragment = new HomeFragment();
            Bundle bundle = new Bundle();
            bundle.putLong("data",catalogs.get(position).getId());
            fragment.setArguments(bundle);
            return fragment;
        }

    }

    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String search = intent.getStringExtra("search");
                if (!TextUtils.isEmpty(search)) {
                    searchTv.setText(search + "");
                }
            }
        }
    }

}